<template>
  <div class="notification-icon" @click="toggleDropdown">
    <div class="icon-wrapper">
      <i class="icon-bell"></i>
      <span v-if="unreadCount > 0" class="badge">{{ unreadCount }}</span>
    </div>
    
    <div v-if="isOpen" class="notification-dropdown">
      <div class="notification-header">
        <h3>我的通知</h3>
        <button v-if="unreadCount > 0" @click.stop="markAllAsRead" class="mark-all-btn">
          全部标为已读
        </button>
      </div>
      
      <div class="notification-filter">
        <button 
          @click.stop="setFilter('all')" 
          :class="{ active: filter === 'all' }"
        >
          全部
        </button>
        <button 
          @click.stop="setFilter('unread')" 
          :class="{ active: filter === 'unread' }"
        >
          未读
        </button>
      </div>
      
      <div class="notification-list" ref="listRef">
        <div v-if="loading" class="loading">
          加载中...
        </div>
        <template v-else>
          <div v-if="notifications.length === 0" class="empty-msg">
            暂无{{ filter === 'unread' ? '未读' : '' }}通知
          </div>
          <notification-item
            v-for="notification in notifications"
            :key="notification.id"
            :notification="notification"
            @update="refreshNotifications"
          />
        </template>
      </div>
      
      <div class="notification-footer">
        <router-link to="/notifications" @click.stop>
          查看全部通知
        </router-link>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue';
import { useNotificationStore } from '../stores/notification';
import NotificationItem from './NotificationItem.vue';

export default {
  name: 'NotificationIcon',
  components: {
    NotificationItem
  },
  setup() {
    const notificationStore = useNotificationStore();
    const isOpen = ref(false);
    const filter = ref('all');
    const listRef = ref(null);
    
    // 计算属性
    const unreadCount = computed(() => notificationStore.unreadCount);
    const notifications = computed(() => notificationStore.notifications);
    const loading = computed(() => notificationStore.loading);
    
    // 方法
    const toggleDropdown = () => {
      isOpen.value = !isOpen.value;
      if (isOpen.value) {
        refreshNotifications();
      }
    };
    
    const refreshNotifications = async () => {
      if (filter.value === 'unread') {
        await notificationStore.fetchNotifications({ isRead: 0 });
      } else {
        await notificationStore.fetchNotifications();
      }
      await notificationStore.fetchUnreadCount();
    };
    
    const markAllAsRead = async () => {
      await notificationStore.readAllNotifications();
      refreshNotifications();
    };
    
    const setFilter = (newFilter) => {
      filter.value = newFilter;
    };
    
    // 关闭下拉框的点击监听器
    const handleClickOutside = (event) => {
      const dropdownEl = listRef.value?.parentNode?.parentNode;
      if (isOpen.value && dropdownEl && !dropdownEl.contains(event.target)) {
        isOpen.value = false;
      }
    };
    
    // 监听筛选器变化
    watch(filter, () => {
      refreshNotifications();
    });
    
    // 周期性检查未读消息
    let interval;
    
    onMounted(() => {
      notificationStore.fetchUnreadCount();
      interval = setInterval(() => {
        notificationStore.fetchUnreadCount();
      }, 60000); // 每分钟检查一次
      
      // 添加点击外部关闭下拉框的事件监听
      document.addEventListener('click', handleClickOutside);
    });
    
    onBeforeUnmount(() => {
      clearInterval(interval);
      document.removeEventListener('click', handleClickOutside);
    });
    
    return {
      isOpen,
      filter,
      unreadCount,
      notifications,
      loading,
      listRef,
      toggleDropdown,
      refreshNotifications,
      markAllAsRead,
      setFilter
    };
  }
}
</script>

<style scoped>
.notification-icon {
  position: relative;
  display: inline-block;
}

.icon-wrapper {
  position: relative;
  cursor: pointer;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.icon-wrapper:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.icon-bell {
  display: inline-block;
  width: 20px;
  height: 20px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9'%3E%3C/path%3E%3Cpath d='M13.73 21a2 2 0 0 1-3.46 0'%3E%3C/path%3E%3C/svg%3E");
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.badge {
  position: absolute;
  top: 6px;
  right: 6px;
  min-width: 16px;
  height: 16px;
  background-color: #f56c6c;
  color: white;
  border-radius: 10px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 4px;
}

.notification-dropdown {
  position: absolute;
  top: 45px;
  right: 0;
  width: 360px;
  max-height: 480px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.notification-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notification-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.mark-all-btn {
  background: none;
  border: none;
  color: #1677ff;
  cursor: pointer;
  font-size: 14px;
}

.mark-all-btn:hover {
  text-decoration: underline;
}

.notification-filter {
  display: flex;
  padding: 8px 16px;
  border-bottom: 1px solid #eee;
}

.notification-filter button {
  padding: 4px 12px;
  margin-right: 8px;
  border: none;
  background: none;
  border-radius: 16px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.notification-filter button.active {
  background-color: #e6f4ff;
  color: #1677ff;
}

.notification-list {
  flex: 1;
  overflow-y: auto;
  max-height: 320px;
}

.loading, .empty-msg {
  padding: 30px 0;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.notification-footer {
  padding: 12px 16px;
  text-align: center;
  border-top: 1px solid #eee;
}

.notification-footer a {
  color: #1677ff;
  text-decoration: none;
  font-size: 14px;
}

.notification-footer a:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .notification-dropdown {
    position: fixed;
    top: 60px;
    left: 0;
    right: 0;
    width: 100%;
    max-height: calc(100% - 60px);
    border-radius: 0;
  }
}
</style> 